/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ChateoController;

import java.net.*;
import java.util.ArrayList;
import ChateoFacadeNI.*;
import ChateoFacadeGUI.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author abdala
 * @author tchordjallian
 */
public class Controller_Old
{

    //The static UNIQUE CONTROLLER
    //The list of user where each user is defined by an id you can find in its own class
    private UsersList userList;
    //The list of messages where each message is defined by an id you can find in its own class
    private ArrayList<ChatMessage> messageList = new ArrayList<ChatMessage>();
    //The debugging state will provide some more verbose
    private static boolean debug = true;
    //Login of the local user
    private String myLogin = "toto";

    //IDs for a user
    InetAddress addr;
    String login;
    //The next two Won't work , will never receive the true login and addr
    User LoggedInUser = new User(addr, login, true);
    User LoggedOutUser = new User(addr, login, false);
    User theNewOne;
    //Facades
    private FacadeGUI facadegui;
    private FacadeNI facadeni;
    //Port : STATIC 
    private static int port = 2014;

    public Controller_Old() {
        //TODO : WAITING FOR GUI This is the version that will generate the whole system
    }

    public Controller_Old(String login, int port) throws SocketException, NullPointerException, UnknownHostException {
        //This is the text version of the Controller
        this.myLogin = login;
        this.port = port;
        //facadeni= new FacadeNI(this,port);

    }
    /* @pa
     * 
     * 
     */

    public String newUser(String remoteLogin, InetAddress remoteAddr) throws UnknownHostException {
        String out = "";
        LoggedInUser.setAddr(remoteAddr);
        LoggedInUser.setLogin(remoteLogin);
        LoggedOutUser.setAddr(remoteAddr);
        LoggedOutUser.setLogin(remoteLogin);

        //We check if the user doesn't already exist in our user list.
        //Ne pas créer un user tant qu'on n'a pas vérifié s'il existe ou pas
        if (userList.contains(LoggedInUser)) {
            System.err.println("The user " + LoggedInUser.getLogin() + " already exists in the list.Please enter a new login");
            //System.exit(-1);
            //Avec un system exit le programme du serveur de l'autre côté crashe ce n'est probablement pas la meilleure solution 
            //je pencherai probablement plus sur un return
            return ("Error existing user in list");

        } else if (userList.contains(LoggedOutUser)) {
            //We create a new user
            userList.get(userList.indexOf(LoggedOutUser)).setLoggingState(true);
        } else {

            //Now, the goal is to add him to the list
            userList.add(theNewOne);
        }
        try {
            //userList.add(theNewOne.getId(),theNewOne);
            //Send the ACK to the user that just got connected with our ID
            sendAck(myLogin, InetAddress.getByName("255.255.255.255"));
        } catch (SocketException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
        //GUI Update
        // TODO WHEN THE GUI WILL BE READY
        //

        if (DebugMode()) {
            System.out.println("User: " + userList.get(userList.indexOf(LoggedOutUser)) + "has been added to the user List");
            out = remoteLogin;
        } else {
            out = remoteLogin;
        }
        return out;

    }

    public String newUserAck(String remoteLogin, InetAddress remoteAddr) throws UnknownHostException {
        String out = "";
        LoggedInUser.setAddr(remoteAddr);
        LoggedInUser.setLogin(remoteLogin);
        LoggedOutUser.setAddr(remoteAddr);
        LoggedOutUser.setLogin(remoteLogin);
        theNewOne.setAddr(remoteAddr);
        theNewOne.setLogin(remoteLogin);

        //We check if the user doesn't already exist in our user list.
        //Ne pas créer un user tant qu'on n'a pas vérifié s'il existe ou pas
        if (userList.contains(LoggedInUser)) {
            System.err.println("The user " + LoggedInUser.getLogin() + " already exists in the list.Please enter a new login");
            //System.exit(-1);
            //Avec un system exit le programme du serveur de l'autre côté crashe ce n'est probablement pas la meilleure solution 
            //je pencherai probablement plus sur un return
            return ("Error existing user in list");

        } else if (userList.contains(LoggedOutUser)) {
            //We create a new user
            userList.get(userList.indexOf(LoggedOutUser)).setLoggingState(true);
            System.out.println("Welcome back " + remoteLogin);
            theNewOne = new User(remoteAddr, remoteLogin);
        } else //Now, the goal is to add him to the listl
        {
            userList.add(theNewOne);
        }

        //Once the user is added to the userlist we can change his state to Logged In
        userList.get(userList.indexOf(LoggedOutUser)).setLoggingState(true);

        //GUI Update
        // TODO WHEN THE GUI WILL BE READY
        //
        if (DebugMode()) {
            System.out.println("User: " + userList.get(userList.indexOf(LoggedOutUser)) + "has been added to the user List");
            out = remoteLogin;
        } else {
            out = remoteLogin;
        }
        return out;
    }

    public void sendAck(String login, InetAddress IPaddr) throws UnknownHostException, SocketException {
        // 
        //-Lancer la methode de la facade qui envoie le ACK
        facadeni.outgoingAck(IPaddr, login);
        //
    }

    //This method is to check if a user has just left
    //public String userLeft(String login, InetAddress IPaddr){
    public boolean userLeft() {
        //String out="";
        //-Utiliser la recherche dans userlist par Login et IP
        if (!userList.contains(LoggedInUser)) {
            //-Changer le status de l'user
            userList.get(userList.indexOf(LoggedInUser)).setLoggingState(false);
            System.out.println("The user " + LoggedInUser.getLogin() + " has left");
        }
        //-Effectuer la MAJ du GUI
        //return out;
        return true;

    }

    /**
     * This method is aimed at enabling to connect a localUser.
     *
     * @throws java.net.SocketException
     * @throws java.net.UnknownHostException
     */
    public void connect() throws NullPointerException, SocketException, UnknownHostException {
        try {
            userList = new UsersList(new User(InetAddress.getLocalHost(), myLogin));
            facadeni.outgoingHello(InetAddress.getByName("255.255.255.255"), myLogin);
            System.out.println("The user " + myLogin + " has been connected \n");
        } catch (SocketException se) {
            System.out.println("Error in creation");
        }

    }

    /**
     * This method is aimed at enabling to disconnect a localUser.
     *
     * @throws java.net.UnknownHostException
     * @throws java.net.SocketException
     */
    public void disconnect() throws UnknownHostException, SocketException {
        facadeni.outgoingBye(InetAddress.getByName("255.255.255.255"), myLogin);
        System.out.println("Disconnection of the user " + myLogin);
    }

    public UsersList getUserList() {
        return userList;
    }

    public String getMyLogin() {
        return myLogin;
    }

    public static boolean DebugMode() {
        return debug;
    }

}
